#! /usr/bin/env python
#coding=utf-8
from ctypes import *
usb_id = 0
dev_addr = 0x80

class USBI2C():
    ch341 = windll.LoadLibrary("./CH341DLLA64.DLL")
    def __init__(self, usb_dev = 0, i2c_dev = 0x5c):
        self.usb_id   = usb_dev
        self.dev_addr = i2c_dev
        self.handler=USBI2C.ch341.CH341OpenDevice(self.usb_id)
        if self.handler != -1:
            print("USB CH341 Open Success! handler:",self.handler)
            USBI2C.ch341.CH341SetStream(self.usb_id, 0x82)
            USBI2C.ch341.CH341CloseDevice(self.usb_id)
        else:
            print("USB CH341 Open Failed!")

    def read(self, addr):
        if USBI2C.ch341.CH341OpenDevice(self.usb_id) != -1:
            obuf = (c_byte * 2)()
            ibuf = (c_byte * 2)()
            obuf[0] = self.dev_addr
            obuf[1] = addr
            USBI2C.ch341.CH341StreamI2C(self.usb_id, 2, obuf, 2, ibuf)
            USBI2C.ch341.CH341CloseDevice(self.usb_id)
            return ibuf[0] & 0xff,ibuf[1] & 0xff
        else:
            print("USB CH341 Open Failed!")
            return 0

    def write(self, addr, dat):
        if USBI2C.ch341.CH341OpenDevice(self.usb_id) != -1:
            obuf = (c_byte * 4)()
            ibuf = (c_byte * 1)()
            obuf[0] = self.dev_addr
            obuf[1] = addr
            obuf[2] = dat[0] & 0xff
            obuf[3] = dat[1] & 0xff
            USBI2C.ch341.CH341StreamI2C(self.usb_id, 4, obuf, 0, ibuf)
            USBI2C.ch341.CH341CloseDevice(self.usb_id)
        else:
            print("USB CH341 Open Failed!")


if __name__ == "__main__":
    iic= USBI2C(0, 0x80)
    rec=iic.read(0x00)
    print(rec)
    print(hex(rec[0] << 8 | rec[1]))
    iic.write(0x00, [0x21,0x8d])
    rec=iic.read(0x00)
    print(rec)
    print(hex(rec[0] << 8 | rec[1]))
    # buf = (c_byte * 200)()
    # iic.ch341.CH341GetDeviceDescr(0,buf,100)
    # print(buf)
    # ch341 = windll.LoadLibrary("./CH341DLLA64.DLL")
    # cmd = (c_ubyte * 4)()
    # ibuf = (c_ubyte * 4)()
    # ibuf = ch341.CH341GetVerIC(usb_id)
    # print(ibuf)